import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { SystemMenuDataItemType, SystemMenuStateType } from './typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElCard,
  ElButton,
  ElIcon,
  ElFormItem,
  ElInput,
  ElSpace,
  ElMessageBox,
  ElMessage
} from 'element-plus'
import { Plus, View, EditPen, Delete, CirclePlus } from '@element-plus/icons-vue'
import ProSaasTable from '~/components/ProSaasTable'
import SystemMenuOptions from './options'
import AliIcon from '~/components/AliIocn'
import useVuexGetters from '~/hooks/useVuexGetters'

export default defineComponent(function SystemMenu() {
  const store = useStore()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const state = reactive<SystemMenuStateType>({
    modalVisible: false,
    type: 'read',
    record: {}
  })
  const formValues = reactive<SystemMenuDataItemType>({})
  const systemMenuState = useVuexGetters('systemMenu', ['menuTypeSelectList', 'menuTypeEnum'])

  // 打开操作弹框
  const handleChangeOptionsModal = (
    type: SystemMenuStateType['type'],
    record?: SystemMenuDataItemType
  ) => {
    state.modalVisible = !state.modalVisible
    state.record = record || {}
    state.type = type
    if (!state.modalVisible) proSaasTableRef.value!?.toSearch()
  }

  // 打开删除消息确认框
  const handleOpenDeleteConfirm = (record?: SystemMenuDataItemType) => {
    if (!record && !proSaasTableRef.value!.selecteds?.length) {
      ElMessage({ type: 'warning', message: '请选择至少一条数据' })
      return
    }
    const params =
      record?.id || proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')
    ElMessageBox.confirm('确定将选择数据删除?', {
      buttonSize: 'small',
      type: 'warning',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(async () => {
        await store.dispatch('systemMenu/DeleteSystemMenuInfo', { ids: params }).then((res) => {
          if (res?.code === 200) {
            proSaasTableRef.value!?.clearSelection?.()
            proSaasTableRef.value!?.toSearch()
            ElMessage({ type: 'success', message: '操作成功' })
          }
        })
      })
      .catch(() => {})
  }

  onMounted(() => {
    // 获取设施类型数据字典
    store.dispatch('systemMenu/GetMenuTypeSelectList')
    // 获取上级菜单树型下拉列表
    store.dispatch('systemMenu/GetMenuTreeByParentId')
  })

  const columns: TableColumnProps<SystemMenuDataItemType>[] = [
    {
      label: '菜单名称',
      prop: 'name'
    },
    {
      label: '路由地址',
      prop: 'path'
    },
    {
      label: '菜单图标',
      prop: 'source',
      render: ({ row }) => (
        <>
          <AliIcon type={row?.source!} />
          &emsp;
          {row?.source}
        </>
      )
    },
    {
      label: '菜单编号',
      prop: 'code'
    },
    {
      label: '菜单类型',
      prop: 'category',
      enumValues: systemMenuState.menuTypeEnum
    },
    {
      label: '菜单排序',
      prop: 'sort'
    },
    {
      label: '操作',
      prop: 'options',
      width: 400,
      render: ({ row }) => (
        <ElSpace>
          <ElButton text type="primary" onClick={() => handleChangeOptionsModal('read', row)}>
            <ElIcon>
              <View />
            </ElIcon>
            &nbsp; 查看
          </ElButton>
          <ElButton text type="primary" onClick={() => handleChangeOptionsModal('update', row)}>
            <ElIcon>
              <EditPen />
            </ElIcon>
            &nbsp; 编辑
          </ElButton>
          <ElButton text type="primary" onClick={() => handleOpenDeleteConfirm(row)}>
            <ElIcon>
              <Delete />
            </ElIcon>
            &nbsp; 删除
          </ElButton>
          <ElButton text type="primary" onClick={() => handleChangeOptionsModal('add', row)}>
            <ElIcon>
              <CirclePlus />
            </ElIcon>
            &nbsp; 新增子项
          </ElButton>
        </ElSpace>
      )
    }
  ]
  return () => (
    <ElCard>
      <ProSaasTable<SystemMenuDataItemType>
        ref={proSaasTableRef}
        columns={columns}
        hasIndex
        dispatchType="systemMenu/GetSystemMenuList"
        dispatchTypeGetListKeys="data"
        rowKey="id"
        // lazy
        searchFormProps={{
          model: formValues
        }}
        searchformResponsiveCol={[
          <ElFormItem key="name" prop="name">
            <ElInput v-model={formValues.name} {...{ maxlength: 50 }} placeholder="菜单名称" />
          </ElFormItem>,
          <ElFormItem key="code" prop="code">
            <ElInput v-model={formValues.code} {...{ maxlength: 50 }} placeholder="菜单编号" />
          </ElFormItem>
        ]}
        headerTitle={
          <>
            <ElButton type="primary" onClick={() => handleChangeOptionsModal('add')}>
              <ElIcon>
                <Plus />
              </ElIcon>
              &nbsp; 新增
            </ElButton>
          </>
        }
      />
      {state.modalVisible && (
        <SystemMenuOptions
          visible={state.modalVisible}
          type={state.type}
          record={state.record}
          onCancel={() => handleChangeOptionsModal('read')}
        />
      )}
    </ElCard>
  )
})
